package pers.mor.tomcat.http;

import pers.mor.tomcat.catalina.Context;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.util.*;

public class ApplicationContext extends BaseServletContext {

    private Map<String, Object> attributesMap;
    private Context context;

    public ApplicationContext(Context context) {
        this.attributesMap = new HashMap<>();
        this.context = context;
    }

    @Override
    public Servlet getServlet(String s) throws ServletException {
        HttpServlet servlet = null;
        try {
            Class<?> aClass = this.context.getWebappClassLoader().loadClass(s);
            servlet = this.context.getServlet(aClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return servlet;
    }

    @Override
    public Enumeration<String> getServletNames() {
        return this.context.getServletNames();
    }

    @Override
    public String getContextPath() {
        return this.context.getPath();
    }

    public void setAttribute(String name, Object value) {
        this.attributesMap.put(name, value);
    }

    public Object getAttribute(String name) {
        return this.attributesMap.get(name);
    }

    public void removeAttribute(String name) {
        this.attributesMap.remove(name);
    }

    public Enumeration<String> getAttributeNames() {
        Set<String> keys = this.attributesMap.keySet();
        return Collections.enumeration(keys);
    }

    public String getRealPath(String path) {
        return new File(this.context.getBase(), path).getAbsolutePath();
    }

}
